interface MsgType {
    type: string,
    params: string
}

class ResultWithPromise extends Promise<MsgType> {
    public on(event: 'close' | 'data' | 'end' | 'error', listener: () => void): ResultWithPromise {
        if (event === 'close') {
            return this;
        }
        if (event === 'data') {
            return this;
        }
        if (event === 'end') {
            return this;
        }
        if (event === 'error') {
            return this;
        }
        return this;
    }
}

class WebClient {
    private handlers: Map<string, (e: MsgType) => void>;
    private ws: WebSocket | null = null;
    private host: string;
    private port: number;

    constructor(host: string, port: number) {
        this.handlers = new Map<string, (e: MsgType) => void>();
        this.host = host;
        this.port = port;
    }

    public Connect(): void {
        this.ws = new WebSocket(`ws://${this.host}:${this.port}`);
        // 连接成功
        this.ws.onopen = (event) => {
        };
        // 接收消息
        this.ws.onmessage = (event) => {
        };
        // 连接关闭
        this.ws.onclose = (event) => {
            // this.ws = null;
        };
        // 错误处理
        this.ws.onerror = (error) => {
        };
    }

    public Disconnect(): void {
        this.ws?.close();
        this.ws = null;
    }

    public Send(message: MsgType): Promise<MsgType> {
        this.ws?.send(JSON.stringify(message));
        return new Promise((resolve, reject) => {
            this.RegisterHandler(message.type, (msg) => {
                resolve(msg);
            });
        })
    }

    private RegisterHandler(type: string, handler: (e: MsgType) => void) {
        this.handlers.set(type, handler);
    }

    private ProcessMessages(message: MsgType) {
        if (!message.type || !message.params) {
            return;
        }
        const handler = this.handlers.get(message.type);
        if (handler) {
            handler(message);
        }
    }
};

export default WebClient;